import { createRouter, createWebHistory } from 'vue-router'
import storage from "@/utils/storage";
import DefaultLayout from "@/layout/default.vue";


const routes = [
  {
    path: '/',
    redirect: '/home'
  },

  {
    path: '/',
    name: '主页',
    component: DefaultLayout,
    children: [{
      path: '/home',
      name: '主页',
      component: () => import('@/views/main/index.vue'),
    }],
    meta: {
      title: '点餐管理系统',
      isAuthRequired: true,
    }
  },
  {
    path: '/',
    component: DefaultLayout,
    children: [{
      path: '/product',
      name: '菜品管理',
      component: () => import('@/views/product/index.vue'),
    }],
    meta: {
      title: '菜品管理',
      isAuthRequired: true,
    }
  },
  {
    path: '/',
    component: DefaultLayout,
    children: [{
      path: '/taocan',
      name: '套餐管理',
      component: () => import('@/views/taocan/index.vue'),
    }],
    meta: {
      title: '套餐管理',
      isAuthRequired: true,
    }
  },

  {
    path: '/',
    component: DefaultLayout,
    children: [{
      path: '/order/grid',
      name: '餐桌',
      component: () => import('@/views/order/grid.vue'),
    }],
    meta: {
      title: '餐桌',
      isAuthRequired: true,
    }
  },

  {
    path: '/',
    component: DefaultLayout,
    children: [{
      path: '/order/list',
      name: '订单管理',
      component: () => import('@/views/order/list.vue'),
    }],
    meta: {
      title: '订单管理',
      isAuthRequired: true,
    }
  },

  {
    path: '/',
    component: DefaultLayout,
    children: [{
      path: '/product/add',
      name: '新增商品',
      component: () => import('@/views/product/add.vue'),
    }],
    meta: {
      title: '管理',
      isAuthRequired: true,
    }
  },
  {
    path: '/',
    component: DefaultLayout,
    children: [{
      path: '/product/edit',
      name: '商品',
      component: () => import('@/views/product/edit.vue'),
    }],
    meta: {
      title: '编辑',
      isAuthRequired: true,
    }
  },
  {
    path: '/login',
    name: '登陆', // 路由名称
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '点餐-登录',
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  let token = storage.getItem('user')
  console.log(`token: ${JSON.stringify(token)}`)
  if (to.meta.isAuthRequired) {
    if (token) {
      next()
    }
    else {
      storage.setItem('referrer', to.fullPath) //储存来源路由
      next('/login');
    }
  } else {
    next();
  }
  document.title = to.meta.title
})

export default router
